<template>
  <div class="inspection-record-view">
    <van-nav-bar
        title="执行记录"
        left-arrow
        @click-left="onBack"
        fixed
    />

    <div class="filter-container">
      <van-dropdown-menu>
        <van-dropdown-item
            v-model="filterOptions.shippingstarttime"
            :options="dateOptions"
        />
      </van-dropdown-menu>
    </div>

    <div class="record-list">
      <van-collapse v-model="activeNames">
        <!-- 处理状态组 -->
        <van-collapse-item title="已处理工单" name="processed">
          <template #title>
            <div class="custom-title">已处理工单</div>
          </template>
          <template v-for="(yearGroup, year) in groupedProcessedTickets">
            <div :key="year" class="year-group">
              <div class="year-title" @click="toggleYear(`processed-${year}`)">
                <span>{{ year }}年</span>
                <van-icon
                    :name="expandedYears.includes(`processed-${year}`) ? 'arrow-up' : 'arrow-down'"
                    class="year-toggle-icon"
                />
              </div>
              <div v-show="expandedYears.includes(`processed-${year}`)" class="year-content">
                <template v-for="(monthGroup, month) in yearGroup">
                  <div :key="`${year}-${month}`" class="month-group">
                    <div class="month-title" @click="toggleMonth(`processed-${year}-${month}`)">
                      <span>{{ month }}月</span>
                      <van-icon
                          :name="expandedMonths.includes(`processed-${year}-${month}`) ? 'arrow-up' : 'arrow-down'"
                          class="month-toggle-icon"
                      />
                    </div>
                    <div v-show="expandedMonths.includes(`processed-${year}-${month}`)" class="month-content">
                      <van-cell
                          v-for="ticket in monthGroup"
                          :key="ticket.id"
                          :title="formatTicketTitle(ticket)"
                          is-link
                          @click="viewRecord(ticket)"
                      />
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </van-collapse-item>

        <!-- 派单状态组 -->
        <van-collapse-item title="已派单工单" name="assigned">
          <template #title>
            <div class="custom-title">已派单工单</div>
          </template>
          <template v-for="(yearGroup, year) in groupedAssignedTickets">
            <div :key="year" class="year-group">
              <div class="year-title" @click="toggleYear(`assigned-${year}`)">
                <span>{{ year }}年</span>
                <van-icon
                    :name="expandedYears.includes(`assigned-${year}`) ? 'arrow-up' : 'arrow-down'"
                    class="year-toggle-icon"
                />
              </div>
              <div v-show="expandedYears.includes(`assigned-${year}`)" class="year-content">
                <template v-for="(monthGroup, month) in yearGroup">
                  <div :key="`${year}-${month}`" class="month-group">
                    <div class="month-title" @click="toggleMonth(`assigned-${year}-${month}`)">
                      <span>{{ month }}月</span>
                      <van-icon
                          :name="expandedMonths.includes(`assigned-${year}-${month}`) ? 'arrow-up' : 'arrow-down'"
                          class="month-toggle-icon"
                      />
                    </div>
                    <div v-show="expandedMonths.includes(`assigned-${year}-${month}`)" class="month-content">
                      <van-cell
                          v-for="ticket in monthGroup"
                          :key="ticket.id"
                          :title="formatTicketTitle(ticket)"
                          is-link
                          @click="viewRecord(ticket)"
                      />
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </van-collapse-item>

        <!-- 退回状态组 -->
        <van-collapse-item title="已退回工单" name="returned">
          <template #title>
            <div class="custom-title">已退回工单</div>
          </template>
          <template v-for="(yearGroup, year) in groupedReturnedTickets">
            <div :key="year" class="year-group">
              <div class="year-title" @click="toggleYear(`returned-${year}`)">
                <span>{{ year }}年</span>
                <van-icon
                    :name="expandedYears.includes(`returned-${year}`) ? 'arrow-up' : 'arrow-down'"
                    class="year-toggle-icon"
                />
              </div>
              <div v-show="expandedYears.includes(`returned-${year}`)" class="year-content">
                <template v-for="(monthGroup, month) in yearGroup">
                  <div :key="`${year}-${month}`" class="month-group">
                    <div class="month-title" @click="toggleMonth(`returned-${year}-${month}`)">
                      <span>{{ month }}月</span>
                      <van-icon
                          :name="expandedMonths.includes(`returned-${year}-${month}`) ? 'arrow-up' : 'arrow-down'"
                          class="month-toggle-icon"
                      />
                    </div>
                    <div v-show="expandedMonths.includes(`returned-${year}-${month}`)" class="month-content">
                      <van-cell
                          v-for="ticket in monthGroup"
                          :key="ticket.id"
                          :title="formatTicketTitle(ticket)"
                          is-link
                          @click="viewRecord(ticket)"
                      />
                    </div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </van-collapse-item>
      </van-collapse>
    </div>
  </div>
</template>

<script>
import { NavBar, DropdownMenu, DropdownItem, Collapse, CollapseItem, Cell, Icon } from 'vant';
import dayjs from 'dayjs';

export default {
  name: 'InspectionRecordView',
  components: {
    [NavBar.name]: NavBar,
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Collapse.name]: Collapse,
    [CollapseItem.name]: CollapseItem,
    [Cell.name]: Cell,
    [Icon.name]: Icon,
  },
  data() {
    return {
      filterOptions: {
        shippingstarttime: null,
      },
      dateOptions: [
        { text: '工单日期', value: null },
        { text: '今天', value: 1 },
        { text: '本周', value: 2 },
        { text: '本月', value: 3 },
      ],
      activeNames: ['processed', 'assigned', 'returned'],
      tickets: [],
      expandedMonths: [],
      expandedYears: [],
    };
  },
  computed: {
    groupedProcessedTickets() {
      return this.groupTicketsByDate(this.tickets.filter(ticket => ticket.shippingstatus === 1));
    },
    groupedAssignedTickets() {
      return this.groupTicketsByDate(this.tickets.filter(ticket => ticket.shippingstatus === 2));
    },
    groupedReturnedTickets() {
      return this.groupTicketsByDate(this.tickets.filter(ticket => ticket.shippingstatus === 3));
    }
  },
  methods: {
    onBack() {
      this.$router.back();
    },
    formatTicketTitle(ticket) {
      return `${ticket.shippinggenerationtime} - 工单号：${ticket.id}`;
    },
    viewRecord(ticket) {
      this.$router.push({
        path: '/details',
        query: { id: ticket.id }
      });
    },
    findAll() {
      // 根据筛选条件处理日期范围
      let dateFilter = {};

      switch (this.filterOptions.shippingstarttime) {
        case 1: // 今天
          dateFilter = {
            startDate: dayjs().startOf('day').format('YYYY-MM-DD HH:mm:ss'),
            endDate: dayjs().endOf('day').format('YYYY-MM-DD HH:mm:ss')
          };
          break;
        case 2: // 本周
          dateFilter = {
            startDate: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
            endDate: dayjs().format('YYYY-MM-DD HH:mm:ss')
          };
          break;
        case 3: // 本月
          dateFilter = {
            startDate: dayjs().subtract(30, 'day').format('YYYY-MM-DD HH:mm:ss'),
            endDate: dayjs().format('YYYY-MM-DD HH:mm:ss')
          };
          break;
        default:
          dateFilter = {};
      }

      // 构建查询参数
      const params = {
        shippingstarttime: dateFilter.startDate || null,
        shippingendtime: dateFilter.endDate || null,
      };

      this.axios.post('http://localhost:9999/api-central-service/shipping/findByCondition', params)
          .then(res => {
            if (res.data.code === 1) {
              this.tickets = res.data.data;
            }
          })
          .catch(err => {
            console.error('获取数据失败:', err);
          });
    },
    groupTicketsByDate(tickets) {
      const grouped = {};
      tickets.forEach(ticket => {
        const date = dayjs(ticket.shippinggenerationtime);
        const year = date.year();
        const month = date.month() + 1; // dayjs 月份从 0 开始

        if (!grouped[year]) {
          grouped[year] = {};
        }
        if (!grouped[year][month]) {
          grouped[year][month] = [];
        }
        grouped[year][month].push(ticket);
      });

      // 对年份和月份进行排序
      return Object.keys(grouped)
          .sort((a, b) => b - a) // 年份降序
          .reduce((acc, year) => {
            acc[year] = Object.keys(grouped[year])
                .sort((a, b) => b - a) // 月份降序
                .reduce((monthAcc, month) => {
                  monthAcc[month] = grouped[year][month];
                  return monthAcc;
                }, {});
            return acc;
          }, {});
    },
    toggleMonth(monthKey) {
      const index = this.expandedMonths.indexOf(monthKey);
      if (index === -1) {
        this.expandedMonths.push(monthKey);
      } else {
        this.expandedMonths.splice(index, 1);
      }
    },
    toggleYear(yearKey) {
      const index = this.expandedYears.indexOf(yearKey);
      if (index === -1) {
        this.expandedYears.push(yearKey);
      } else {
        this.expandedYears.splice(index, 1);
      }
    },
  },
  watch: {
    'filterOptions.shippingstarttime'() {
      this.findAll();
    }
  },
  mounted() {
    this.findAll();
  }
};
</script>

<style scoped>
.inspection-record-view {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-top: 46px;
}

.filter-container {
  position: sticky;
  top: 46px;
  z-index: 100;
  background-color: #fff;
}

.record-list {
  padding: 16px;
}

.custom-title {
  text-align: left;
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin-left: -16px;
}

:deep(.van-collapse-item__title) {
  font-size: 16px;
  font-weight: bold;
}

:deep(.van-cell) {
  padding: 12px 0;
}

:deep(.van-dropdown-menu) {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

:deep(.van-collapse-item__content) {
  padding-left: 0;
  padding-right: 0;
}

:deep(.van-cell__title) {
  text-align: left;
}

.year-group {
  margin-bottom: 16px;
}

.year-title {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  padding: 8px 16px;
  background-color: #f7f8fa;
  margin: 8px 0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.year-toggle-icon {
  transition: transform 0.3s;
}

.year-content {
  transition: all 0.3s ease;
}

.month-group {
  margin-bottom: 12px;
}

.month-title {
  font-size: 14px;
  color: #666;
  padding: 4px 16px;
  background-color: #f7f8fa;
  margin: 4px 0;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.month-toggle-icon {
  transition: transform 0.3s;
}

.month-content {
  transition: all 0.3s ease;
}

:deep(.van-cell) {
  padding: 12px 16px;
}

:deep(.van-collapse-item__content) {
  padding: 0;
}

.year-title, .month-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
}

:deep(.van-icon) {
  font-size: 14px;
  color: #969799;
  transition: transform 0.3s;
}

:deep(.van-collapse-item__title:active) {
  background-color: #f7f8fa;
}
</style>